import axios from "axios";
import { ElMessage } from "element-plus";
import { clearStorageLoginInfo } from "@/utils/token";

const service = axios.create({
  // baseURL: "http://localhost:5201/api",
  baseURL: "https://java.baoyierp.com/api",
  timeout: 60000,
});
service.interceptors.request.use(
  async function (config: any) {
    const { baoyiplus_accessToken } = await chrome.storage.sync.get([
      "baoyiplus_accessToken",
    ]);
    if (baoyiplus_accessToken) {
      config.headers.Authorization = `Bearer ${baoyiplus_accessToken}`;
    }
    return config;
  },
  function (error: any) {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  async function (response: any) {
    let res = response.data;
    const { __tips = true } = response.config || {};
    const { code } = res;
    const errorText = res.msg || res.message;
    if (code != 0) {
      if (__tips) {
        ElMessage.error(errorText);
      }

      return Promise.reject(res);
    } else if (code === 401) {
      ElMessage.error(errorText);
      clearStorageLoginInfo();
      return Promise.reject(res);
    } else {
      return res;
    }
  },
  function (error: any) {
    console.log("error", error);
    if (error.message.includes("timeout")) {
      ElMessage.error("请求超时");
    } else {
      let data = error.response && error.response.data;
      const errorText = data ? data.msg || data.message : error.message;
      ElMessage.error(errorText);
      if (data?.code === 401) {
        clearStorageLoginInfo();
      }
    }
    return Promise.reject(error);
  }
);
export default service;
